package demo.ioc.my.core.web;

import demo.ioc.my.core.ctx.DefaultApplicationContext;
import demo.ioc.my.core.ctx.WebApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;

/**
 * Created by 张少昆 on 2018/3/18.
 */
@WebServlet( urlPatterns = "/**" )
public class DispatcherServlet extends HttpServlet {

    DefaultApplicationContext defaultApplicationContext;
    WebApplicationContext webApplicationContext;

    @Override
    public void init() throws ServletException{
        //简化，不考虑配置，默认拦截所有
        // 先创建基础ApplicationContext，再创建WebApplicationContext
        defaultApplicationContext = new DefaultApplicationContext();
        webApplicationContext = new WebApplicationContext();
        webApplicationContext.setParentApplicationContext(defaultApplicationContext);

        String contextPath = getServletContext().getContextPath();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        super.doGet(req, resp);
        // String contextPath = req.getContextPath();
        // String pathInfo = req.getPathInfo();
        // String requestURI = req.getRequestURI();
        // String requestURL = req.getRequestURL().toString();
        // URL url=new URL(requestURL);
        // String path = url.getPath();
        String servletPath = req.getServletPath();

        RequestMappingInfo info = webApplicationContext.URL_REQUESTMAPPING_MAP.get(servletPath);//完全严格匹配！
        if(info==null){
            PrintWriter writer = resp.getWriter();
            writer.write("ERROR!wrong URL!");
            writer.flush();
            return;
        }
        try{
            Object result = info.getMethod().invoke(info.getInstance()); //FIXME 没考虑参数！这里应该反射拿到方法的参数！以后再做。
        } catch(IllegalAccessException e){
            e.printStackTrace();
        } catch(InvocationTargetException e){
            e.printStackTrace();
        }
    }
}
